WorkerScript.onMessage = function(message) {
    if (!message.spotInCollection) {
        //console.log("adding")
        try {
            doAddToCollection(message);
        } catch(err) {
            // don't care
        }
    }
    if (message.userMessage.length > 0) {
        //console.log("adding review")
        doAddReview(message)
    }
}


function doAddToCollection(message) {
    var xhr = new XMLHttpRequest;
    xhr.open("POST", url);
    xhr.onreadystatechange = function() {
        try {
            if (xhr.readyState == XMLHttpRequest.DONE) {
                var response = JSON.parse(xhr.responseText);
                WorkerScript.sendMessage({ 'result': 'SUCCESS' });
            }
        } catch(err) {
            // should not care
            WorkerScript.sendMessage({ 'result': 'FAILURE', 'message': err });
        }
    }
    xhr.send();
}


function doAddReview(message) {
    var xhr = new XMLHttpRequest;
    var url = message.g.serverAPI + "poi/" + message.spotId + "/comments?oauth_token=" + message.g.token;

    var params = '{"comment":{"body":"' + message.userMessage + '"}}';

    xhr.open("POST", url);
    xhr.setRequestHeader("Content-type", "application/json");
    xhr.setRequestHeader("Content-length", message.userMessage.length);
    xhr.setRequestHeader("Connection", "close");
    xhr.onreadystatechange = function() {
        try {
            if (xhr.readyState == XMLHttpRequest.DONE) {
                // console.log(xhr.responseText)
                var response = JSON.parse(xhr.responseText);
                WorkerScript.sendMessage({ 'result': 'SUCCESS' });
            }
        } catch(err) {
            WorkerScript.sendMessage({ 'result': 'FAILURE', 'message': err });
        }
    }
    xhr.send(params);
}
